<template>
  <div class="chatmessage">
    <div class="chatmessage-header">
      <div class="chatmessagehead">
        <div class="chatmessagehead-img">
          <el-avatar
            v-if="chatmessagedata.board_img != ''"
            :src="chatmessagedata.board_img"
          />
          <el-avatar v-else>{{
            chatmessagedata.board_name != ""
              ? chatmessagedata.board_name[0]
              : chatmessagedata.user_nick[0]
          }}</el-avatar>
        </div>
        <div class="chatmessagehead-text">
          <div style="font-size: 16px">
            <span>{{
              chatmessagedata.board_name != ""
                ? chatmessagedata.board_name
                : chatmessagedata.user_nick
            }}</span>
          </div>
          <div style="font-size: 13px"></div>
        </div>
      </div>
    </div>
    <div class="chatmessage-content">
      <div class="messagediv">
        <el-scrollbar
          height="100%"
          view-class="messageview"
          ref="scrollbar"
          @scroll="handleScroll"
        >
          <div v-if="loadingMore" class="loadingmore">加载中...</div>
          <div v-if="hasMore" class="loadingmore">没有更多数据</div>
          <div v-if="hasMoreerror" class="loadingmore" style="color: red">
            没有更多数据
          </div>
          <div
            v-for="(item, index) in chatmessagedata.data"
            :class="messagedivclass(item, index)"
            :key="index"
          >
            <div
              v-if="item.type != 'read' && item.type != 'delete'"
              class="message-row"
            >
              <div
                class="message-status"
                v-if="item.userid == activeaccount.bid_rid"
              >
                <div class="message-type">
                  {{ getstatusmessage(index, item) }}
                </div>
                <div class="message-time">{{ formatTime(item.time) }}</div>
              </div>
              <div v-if="item.userid != activeaccount.bid_rid">
                <el-avatar
                  v-if="chatmessagedata.board_img != ''"
                  :src="chatmessagedata.board_img"
                />
                <el-avatar v-else>{{
                  chatmessagedata.board_name != ""
                    ? chatmessagedata.board_name[0]
                    : chatmessagedata.user_nick[0]
                }}</el-avatar>
              </div>
              <div
                class="message-content"
                v-if="
                  item.type == 'text' &&
                  item.msg != '傳送一則商品訊息' &&
                  item.msg != '傳送一則訂單訊息'
                "
              >
                <span>{{ item.msg }}</span>
              </div>

              <div
                class="message-content-goods"
                v-if="item.type == 'text' && item.msg == '傳送一則商品訊息'"
              >
                <div class="message-goods">
                  <div class="message-goods-id">
                    <span style="font-size: 16px; font-weight: 600"
                      >商品id : </span
                    >{{ item.pid }}
                  </div>
                  <div class="message-goods-content">
                    <div>
                      <el-image
                        style="width: 100px"
                        :src="getgoodsimg(item.pid)"
                      />
                    </div>
                    <div class="message-goods-text">
                      <div class="message-goods-goodname">
                        <el-scrollbar height="100%">
                          <span>{{ getgoodsname(item.pid) }}</span>
                        </el-scrollbar>
                      </div>
                      <div class="message-goods-price">
                        {{ getgoodsprice(item.pid) }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <div
                class="message-content-oders"
                v-if="item.type == 'text' && item.msg == '傳送一則訂單訊息'"
              >
                <div class="message-goods">
                  <div class="message-goods-id">
                    <span style="font-size: 16px; font-weight: 600"
                      >订单id : </span
                    >{{ getorderid(item.oid) }}
                  </div>
                  <div class="message-goods-content">
                    <div>
                      <el-image
                        style="width: 100px"
                        :src="getorderimg(item.oid)"
                      />
                    </div>
                    <div class="message-goods-text">
                      <div class="message-goods-goodname">
                        <el-scrollbar height="100%">
                          <span>{{ getordername(item.oid) }}</span>
                        </el-scrollbar>
                      </div>
                      <div class="message-goods-price">
                        {{ getorderprice(item.oid) }}
                      </div>
                    </div>
                  </div>
                  <div class="order-url">
                    <div class="orderurl-title">订单状态：</div>
                    <div
                      class="orderurl-url"
                      v-html="getorderstatus(item.oid)"
                    ></div>
                  </div>
                  <div class="order-url" style="margin-top: 8px">
                    <div class="orderurl-title">订单链接：</div>
                    <div class="orderurl-url">
                      <span
                        >https://mybid.ruten.com.tw/master/view_transaction.php?tno={{
                          getorderid(item.oid)
                        }}</span
                      >
                    </div>
                  </div>
                </div>
              </div>

              <div class="message-content-img" v-if="item.type == 'img'">
                <el-image
                  class="messageimng"
                  :src="item.msg"
                  alt=""
                  :preview-src-list="srcListfun(item.msg)"
                />
              </div>
              <div class="message-content-img" v-if="item.type == 'sticker'">
                <el-image
                  class="messagesticker"
                  :src="expressionimg[item.sid]"
                  alt=""
                />
              </div>

              <div
                class="message-status"
                v-if="item.userid != activeaccount.bid_rid"
              >
                <div class="message-type">
                  {{ getstatusmessage(index, item) }}
                </div>
                <div class="message-time">{{ formatTime(item.time) }}</div>
              </div>
            </div>
          </div>
        </el-scrollbar>
      </div>
    </div>
    <div class="chatmessage-footer">
      <Editinput />
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  onMounted,
  ref,
  reactive,
  provide,
  inject,
  nextTick,
  watch,
} from "vue";
import Editinput from "@/views/message/editinput.vue";

import { ipc } from "@/utils/ipcRenderer";
import { ipcApiRoute } from "@/api/main.js";

const chatmessagedata = inject<any>("chatmessagedata");
const activeaccount = inject<any>("activeaccount");
const messageList = inject<any>("messageList");
const displayedContacts = inject<any>("displayedContacts");

const expressionimg = ref({
  s20180806g00101: "https://im.rimg.com.tw/im/sticker/1/1.png",
  s20180806g00102: "https://im.rimg.com.tw/im/sticker/1/2.png",
  s20180806g00103: "https://im.rimg.com.tw/im/sticker/1/3.png",
  s20180806g00104: "https://im.rimg.com.tw/im/sticker/1/4.png",
  s20180806g00105: "https://im.rimg.com.tw/im/sticker/1/5.png",
  s20180806g00106: "https://im.rimg.com.tw/im/sticker/1/6.png",
  s20180806g00107: "https://im.rimg.com.tw/im/sticker/1/7.png",
  s20180806g00108: "https://im.rimg.com.tw/im/sticker/1/8.png",
  s20180806g00109: "https://im.rimg.com.tw/im/sticker/1/9.png",
  s20180806g00110: "https://im.rimg.com.tw/im/sticker/1/10.png",
  s20180806g00111: "https://im.rimg.com.tw/im/sticker/1/11.png",
  s20180806g00112: "https://im.rimg.com.tw/im/sticker/1/12.png",
  s20180806g00113: "https://im.rimg.com.tw/im/sticker/1/13.png",
  s20180806g00114: "https://im.rimg.com.tw/im/sticker/1/14.png",
  s20180806g00115: "https://im.rimg.com.tw/im/sticker/1/15.png",
  s20180806g00116: "https://im.rimg.com.tw/im/sticker/1/16.png",
  s20180806g00117: "https://im.rimg.com.tw/im/sticker/1/17.png",
  s20180806g00118: "https://im.rimg.com.tw/im/sticker/1/18.png",
  s20180806g00119: "https://im.rimg.com.tw/im/sticker/1/19.png",
  s20180806g00120: "https://im.rimg.com.tw/im/sticker/1/20.png",
});

const srcListfun = (msg) => {
  let a = [msg];
  return a;
};

const gooddetails = ref([]);
const orderdetails = ref([]);
const scrollbar = ref(null);

const loadingMore = ref(false);
const hasMore = ref(false);
const hasMoreerror = ref(false);
const ishasMore = ref(0);

watch(
  () => chatmessagedata.value.data,
  (newValue, oldValue) => {
    // console.log("data 属性变化:", newValue);
    getgoodslist();
    getorderlist();
  }
);
const messagedivclass = (item, index) => {
  chatmessagedata.value.unread_count = 0;
  let foundIndex2 = displayedContacts.value.findIndex(
    (item3) => item3.id === chatmessagedata.value.id
  );
  if (foundIndex2 != -1) {
    const foundItem = displayedContacts.value[foundIndex2];
    foundItem.unread_count = 0;
  }

  if (index + 1 == chatmessagedata.value.data.length) {
    // console.log(item);

    // console.log(chatmessagedata.value);
    // console.log(activeaccount.value);

    if (item.type == "read" || item.type == "delete") {
      if (item.to[0] == activeaccount.value.bid_rid) {
        let data = {
          to: chatmessagedata.value.id,
          userid: activeaccount.value.bid_rid,
          cookie: activeaccount.value.cookie,
          type: "read",
          msg: "",
        };
        // // console.log(data);

        ipc.invoke(ipcApiRoute.sendmessage, data).then((res) => {
          // console.log(res);
        });
      }
    } else {
      if (item.to[0] != activeaccount.value.bid_rid) {
        let data = {
          to: chatmessagedata.value.id,
          userid: activeaccount.value.bid_rid,
          cookie: activeaccount.value.cookie,
          type: "read",
          msg: "",
        };
        // // console.log(data);

        ipc.invoke(ipcApiRoute.sendmessage, data).then((res) => {
          // console.log(res);
        });
      }
    }

    // if (
    //   item.type != "read" &&
    //   item.type != "delete" &&
    //   item.to[0] != activeaccount.value.id
    // ) {
    //   // console.log(chatmessagedata.value.id);
    //   let data = {
    //     to: chatmessagedata.value.id,
    //     userid: activeaccount.value.bid_rid,
    //     cookie: activeaccount.value.cookie,
    //     type: 'read',
    //     msg: '',
    //   };
    //   // // console.log(data);

    //   ipc.invoke(ipcApiRoute.sendmessage, data).then((res) => {
    //     // console.log(res);

    //   });
    // }
  }

  if (item.userid == activeaccount.value.bid_rid) {
    return "messageright";
  } else {
    return "messageleft";
  }
};

const getgoodslist = () => {
  let messagedata = chatmessagedata.value.data;
  let ids = [];
  let unids = "";
  messagedata.forEach((item) => {
    if (item.type == "text" && item.msg == "傳送一則商品訊息") {
      ids.push(item.pid);
    }
  });
  unids = [...new Set(ids)].join(",");
  if (unids != "") {
    ipc
      .invoke(ipcApiRoute.getgoodsitems, {
        ids: unids,
      })
      .then((res) => {
        if (res != "") {
          let jsonres = JSON.parse(res);
          if (jsonres.status == "success") {
            const combinedArray = [...gooddetails.value, ...jsonres.data];

            // 使用 reduce 方法进行去重，根据 id 属性
            const uniqueArray = combinedArray.reduce((acc, current) => {
              // 判断当前对象的 id 是否已经存在于 acc 中的对象中
              const isExist = acc.some((item) => item.id === current.id);
              if (!isExist) {
                // 如果不存在则添加到 acc 中
                acc.push(current);
              }
              return acc;
            }, []);
            gooddetails.value = combinedArray;
          }
        }
      });
  }
};

const getgoodsimg = (id) => {
  let url = "";
  gooddetails.value.forEach((item) => {
    if (item.id == id) {
      url = item.images.url[0];
    }
  });
  return url;
};

const getgoodsname = (id) => {
  let name = "";
  gooddetails.value.forEach((item) => {
    if (item.id == id) {
      name = item.name;
    }
  });
  return name;
};

const getgoodsprice = (id) => {
  let price = "";
  gooddetails.value.forEach((item) => {
    if (item.id == id) {
      let min = item.goods_price_range.min;
      let max = item.goods_price_range.max;
      if (min != 0 && min != null && max != 0 && max != null) {
        price = `$${min} - $${max}`;
      } else {
        if (min != 0 && min != null) {
          price = `$${min}`;
        } else {
          price = `$${max}`;
        }
      }
    }
  });
  return price;
};

const getorderlist = () => {
  let messagedata = chatmessagedata.value.data;
  let oids = [];
  messagedata.forEach((item) => {
    if (item.type == "text" && item.msg == "傳送一則訂單訊息") {
      oids.push(item.oid);
    }
  });

  getorderlistfor(oids, 0);
};

const getorderlistfor = (oids, num) => {
  if (oids.length > num) {
    let oid = oids[num];
    // console.log(oid);

    let match = oid.match(/([^:]+)\s*:\s*(.+)/);
    if (match) {
      let type = {
        type: match[1].trim(),
      };
      let no = {
        no: match[2].trim(),
      };
      ipc
        .invoke(ipcApiRoute.getorderitems, {
          type: type,
          no: no,
          cookie: activeaccount.value.cookie,
        })
        .then((res) => {
          if (res != "") {
            let resjson = JSON.parse(res);
            // console.log(resjson);

            let exists = orderdetails.value.some((obj) => obj.oid === oid);
            if (!exists) {
              let a = {
                oid: oid,
                no: match[2].trim(),
                data: resjson,
              };
              orderdetails.value.push(a);
            }

            let numi = num + 1;
            getorderlistfor(oids, numi);
          }
        });
    }
  } else {
    // console.log(orderdetails.value);
  }
};

const getorderid = (oid) => {
  let id = "";
  orderdetails.value.forEach((item) => {
    if (item.oid == oid) {
      id = item.no;
    }
  });
  return id;
};

const getorderimg = (oid) => {
  let url = "";
  orderdetails.value.forEach((item) => {
    if (item.oid == oid) {
      url = item.data.img;
    }
  });
  return url;
};

const getordername = (oid) => {
  let name = "";
  orderdetails.value.forEach((item) => {
    if (item.oid == oid) {
      name = item.data.g_name;
    }
  });
  return name;
};

const getorderprice = (oid) => {
  let price = "";
  orderdetails.value.forEach((item) => {
    if (item.oid == oid) {
      price = `$${item.data.amount}`;
    }
  });
  return price;
};

const getorderstatus = (oid) => {
  let status = "";
  orderdetails.value.forEach((item) => {
    if (item.oid == oid) {
      status = item.data.trans_status;
    }
  });

  var txt = document.createElement("textarea");
  txt.innerHTML = status;

  return txt.value;
};

const getstatusmessage = (index, item) => {
  let str = "";
  // // console.log(chatmessagedata.value);

  for (let i = index; i < chatmessagedata.value.data.length; i++) {
    if (
      chatmessagedata.value.data[i].type == "read" &&
      chatmessagedata.value.data[i].userid == item.to[0]
    ) {
      str = "已读";
    }
  }
  return str;
};

const scrollToBottom = async () => {
  await nextTick(); // 等待 DOM 更新完成
  const el = scrollbar.value.$el; // 获取 el-scrollbar 的原生 DOM 元素
  scrollbar.value.setScrollTop(el.children[0].children[0].scrollHeight);
};

const handleScroll = (event) => {
  let scrollTop = event.scrollTop;

  if (scrollTop == 0 && ishasMore.value == 0) {
    loadingMore.value = true;
    hasMore.value = false;
    let data = chatmessagedata.value.data;
    if (data.length > 0) {
      let timestamp = Math.floor(data[0].timestamp);
      // console.log(chatmessagedata.value);

      ipc
        .invoke(ipcApiRoute.getoldmessage, {
          timestamp: timestamp,
          cookie: activeaccount.value.cookie,
          bid_rid: activeaccount.value.bid_rid,
          id: chatmessagedata.value.id,
        })
        .then((res) => {
          if (res != "") {
            let resjson = JSON.parse(res);
            if (resjson.length > 0) {
              let combinedArray = [...resjson, ...data];
              chatmessagedata.value.data = combinedArray;
              loadingMore.value = false;
              hasMore.value = false;
              hasMoreerror.value = false;
              // console.log(messageList.value);
            } else {
              loadingMore.value = false;
              hasMore.value = true;
              hasMoreerror.value = false;
              ishasMore.value = 1;
            }
          } else {
            hasMoreerror.value = true;
            loadingMore.value = false;
            hasMore.value = false;
          }
        });
    } else {
      loadingMore.value = false;
      hasMore.value = true;
      hasMoreerror.value = false;
      ishasMore.value = 1;
    }
  }
};

const formatTime = (dateTimeStr) => {
  const currentDate = new Date();
  const inputDate = new Date(dateTimeStr);

  // 判断是否是今天
  if (isSameDay(currentDate, inputDate)) {
    const hour = inputDate.getHours();
    const minute = inputDate.getMinutes();
    const second = inputDate.getSeconds();
    let period = "";

    // 判断是凌晨、上午、下午还是晚上
    if (hour < 5) {
      period = "凌晨";
    } else if (hour < 12) {
      period = "上午";
    } else if (hour < 18) {
      period = "下午";
    } else {
      period = "晚上";
    }

    // 格式化时间
    const formattedTime = `${period}${hour}:${formatDigits(
      minute
    )}:${formatDigits(second)}`;
    return formattedTime;
  }

  // 判断是否是昨天
  const yesterday = new Date(currentDate);
  yesterday.setDate(currentDate.getDate() - 1);
  if (isSameDay(yesterday, inputDate)) {
    const formattedTime = `昨天 ${formatTimeOfDay(inputDate)}`;
    return formattedTime;
  }

  // 判断是否是今年
  if (currentDate.getFullYear() === inputDate.getFullYear()) {
    const formattedTime = `${formatDate(inputDate)} ${formatTimeOfDay(
      inputDate
    )}`;
    return formattedTime;
  }

  // 如果是去年或更早
  const formattedTime = `${inputDate.getFullYear()}/${formatDate(
    inputDate
  )} ${formatTimeOfDay(inputDate)}`;
  return formattedTime;
};

// 辅助函数：判断两个日期是否是同一天
const isSameDay = (date1, date2) => {
  return (
    date1.getFullYear() === date2.getFullYear() &&
    date1.getMonth() === date2.getMonth() &&
    date1.getDate() === date2.getDate()
  );
};

// 辅助函数：格式化日期为 MM/DD 格式
const formatDate = (date) => {
  const month = date.getMonth() + 1;
  const day = date.getDate();
  return `${formatDigits(month)}/${formatDigits(day)}`;
};

// 辅助函数：格式化时间为 HH:mm:ss 格式
const formatTimeOfDay = (date) => {
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();
  return `${formatDigits(hour)}:${formatDigits(minute)}:${formatDigits(
    second
  )}`;
};

// 辅助函数：确保数字是两位数，不足补零
const formatDigits = (num) => {
  return num < 10 ? `0${num}` : num;
};

onMounted(() => {
  ishasMore.value = 0;
  getgoodslist();
  getorderlist();
  scrollToBottom();
  // console.log(chatmessagedata.value);
});
</script>

<style scoped>
.chatmessage {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 93%;
  padding: 0;
  margin: 0;
  border-right: 1px solid #e4e7ed;
  border-bottom: 1px solid #e4e7ed;
}
.chatmessage-header {
  width: 100%;
  height: 10%;
  overflow: hidden;
  background-color: #ff8a07;
}
.chatmessagehead-img {
  width: 50px;
}
.chatmessagehead-text {
  height: 100%;
  width: calc(100% - 50px);
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.chatmessagehead-text div {
  display: flex;
  align-items: center;
  white-space: nowrap;
  color: #fff;
  padding: 2px 0;
  width: 100%;
}
.chatmessagehead-text div span {
  white-space: nowrap; /* 不允许文本换行 */
  overflow: hidden; /* 超出部分隐藏 */
  text-overflow: ellipsis; /* 显示省略号 */
}

.chatmessagehead {
  height: 100%;
  display: flex;
  align-items: center;
}
.chatmessage-content {
  width: 100%;
  height: 65%;
  background-color: #f3f3f3;
}
.chatmessage-footer {
  width: 100%;
  height: 24%;
  /* background-color: black; */
}

.messagediv {
  height: 100%;
}

.messageright,
.messageleft {
  width: 98%;
}
.message-status {
  height: 100%;
  padding: 0 5px;
  font-size: 10px;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  color: #a8abb2;
}

/* .message-type{
  text-align: left;
} */

.messageleft .message-status {
  text-align: left;
}
.messageright .message-status {
  text-align: right;
}

.message-time {
  margin-top: 5px;
}

.messageright {
  display: flex;
  justify-content: flex-end;
}

.messageleft {
  display: flex;
  justify-content: flex-start;
  margin-left: 10px;
}
/* .messageright .message-row{
  width: calc( 100% - 30px );
} */
.message-row {
  display: flex;
  padding: 8px 0;
  align-items: flex-start;
}

.messageright .message-row {
  display: flex;
  justify-content: flex-end;
}

.message-content {
  font-size: 14px;
  display: flex;
  width: auto;
  max-width: 500px;
}
.message-content-goods {
  width: auto;
  max-width: 490px;
  font-size: 14px;
  display: flex;
  background-color: #fff;
  margin-left: 10px;
  margin-right: 20px;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
}

.message-content-oders {
  width: auto;
  max-width: 490px;
  font-size: 14px;
  display: flex;
  background-color: #fff;
  margin-left: 10px;
  margin-right: 20px;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
}
.message-content-img {
  font-size: 14px;
  display: flex;
  padding: 0 8px;
}

.message-content span {
  text-align: left;
}

.messageleft .message-content {
  background-color: #fff;
  color: black;
  padding: 8px;
  border-radius: 5px;
  margin-left: 10px;
  margin-right: 10px;
  /* width: 60%; */
}

.messageright .message-content {
  background-color: #3679e1;
  color: #fff;
  padding: 8px;
  border-radius: 5px;
  margin-right: 10px;
  margin-left: 10px;
  /* width: 60%; */
}

.messageimng {
  width: 200px;
}
.messagesticker {
  width: 150px;
}

.message-goods {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  padding: 10px;
}
.message-goods-id {
  text-align: left;
  width: 100%;
  padding: 5px 0;
  border-bottom: 1px solid #ebeef5;
}

.message-goods-content {
  display: flex;
  padding: 10px;
}
.message-goods-text {
  padding-left: 10px;
}
.message-goods-goodname {
  height: 60%;
  text-align: left;
}

.message-goods-price {
  margin-top: 10px;
  text-align: left;
  color: #fe7914;
  font-weight: 500;
  line-height: 1.5;
  letter-spacing: 1px;
  font-size: 16px;
}

.order-url {
  display: flex;
  width: 100%;
  font-size: 13px;
}
.orderurl-title {
  width: 80px;
}
.orderurl-url {
  flex: 1;
  text-align: left;
  overflow-wrap: anywhere;
}
.orderurl-url span {
  text-align: left;
}

.loadingmore {
  font-size: 13px;
  padding: 10px 0;
  color: #909399;
}
</style>